package cn.lichenfei.fxui.controls.skin;

import cn.lichenfei.fxui.controls.CFCheckBox;
import com.sun.javafx.scene.control.behavior.BehaviorBase;
import com.sun.javafx.scene.control.behavior.ButtonBehavior;
import javafx.animation.ScaleTransition;
import javafx.scene.control.Label;
import javafx.scene.control.SkinBase;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.util.Duration;

public class CFCheckBoxSkin extends SkinBase<CFCheckBox> {

    private HBox container;
    private StackPane box;
    private StackPane mark;
    private Label label;
    // 动画
    private ScaleTransition scaleTransition;

    private final BehaviorBase<CFCheckBox> behavior;


    public CFCheckBoxSkin(CFCheckBox control) {
        super(control);
        behavior = new ButtonBehavior<>(control);
        createNode(control);
        getChildren().setAll(container);
        setAnimationInfo();
    }

    @Override
    public void dispose() {
        super.dispose();
        if (behavior != null) {
            behavior.dispose();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void layoutChildren(final double x, final double y,
                                  final double w, final double h) {
        super.layoutChildren(x, y, w, h);
    }

    private void createNode(CFCheckBox cfCheckBox) {
        mark = new StackPane();
        box = new StackPane(mark);
        label = new Label();
        label.textProperty().bind(cfCheckBox.textProperty());
        labelManaged(label.getText());
        label.textProperty().addListener((observableValue, s, t1) -> labelManaged(t1));
        container = new HBox(box, label);
        //class
        mark.getStyleClass().add("mark");
        //label.getStyleClass().add("label");
        box.getStyleClass().add("box");
        container.getStyleClass().add("container");
    }

    private void labelManaged(String val) {
        boolean b = val != null && !"".equals(val);
        label.setManaged(b);
        label.setVisible(b);
    }

    private void setAnimationInfo() {
        // 测试：
        CFCheckBox skinnable = getSkinnable();
        if (!skinnable.isSelected()) {
            mark.setScaleX(0);
            mark.setScaleY(0);
        }
        scaleTransition = new ScaleTransition(Duration.millis(200), mark);

        skinnable.selectedProperty().addListener((observableValue, aBoolean, t1) -> {
            if (t1) {
                scaleTransition.setToX(1);
                scaleTransition.setToY(1);
                scaleTransition.setFromX(0);
                scaleTransition.setFromY(0);
                scaleTransition.play();
            } else {
                mark.setScaleX(0);
                mark.setScaleY(0);
            }
        });
    }
}
